package com.b2c.common.third.sender;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 描述：
 * 名传短信client
 *
 * @author qlp
 * @date 2018-10-23 下午2:08
 */
public class SMSHttpClient {

    private static Logger logger = LoggerFactory.getLogger(SMSHttpClient.class);

    private static final String userId = "201247";
    private static final String password = "087979cdce16d41cd897ad78a33a46e4_qbz927";
    private static final String serverUrl = "http://112.74.139.4:8002/sms3_api/jsonapi/jsonrpc2.jsp";
    private static final String METHOD_POST = "POST";
    private static final int connectionTimeout = 10000;
    private static final int readTimeOut = 60000;

    /**
     * 发送短信验证码
     *
     * @param mobile  手机号
     * @param content 短信内容
     * @return 返回0代表成功，其他代表错误
     */
    public static Integer sendCodeSMS(String mobile, String content) throws IOException {
        logger.info("发送短信：" + content);
        JSONObject submitContent = new JSONObject();
        submitContent.put("content", content);
        submitContent.put("phone", mobile);
        JSONArray array = new JSONArray();
        array.add(submitContent);
        return sendSMS(array);
    }

    /**
     * 发送短信
     *
     * @param content
     * @return
     */
    private static Integer sendSMS(JSONArray content) {
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod(METHOD_POST);
            connection.setAllowUserInteraction(false);
            connection.setInstanceFollowRedirects(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(connectionTimeout);// 连接超时时间
            connection.setReadTimeout(readTimeOut);// 读取结果超时时间
            // 设置使用标准编码格式编码参数的名-值对
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setDoInput(true);
            connection.setDoOutput(true);

            // 连接
            connection.connect();

            JSONObject sendContent = new JSONObject();
            sendContent.put("id", 1);
            sendContent.put("method", "send");

            JSONObject params = new JSONObject();
            params.put("userid", userId);
            params.put("password", password);
            params.put("submit", content);

            sendContent.put("params", params);

            String sendString = sendContent.toJSONString();

            OutputStream out = connection.getOutputStream();
            out.write(sendString.getBytes());
            out.flush();
            out.close();
            // 从连接中读取响应信息
            String msg = "";
            int code = connection.getResponseCode();
            if (code == 200) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
                String line;

                while ((line = reader.readLine()) != null) {
                    msg += line + "\n";
                }
                reader.close();
            }
            // 5. 断开连接
            connection.disconnect();

            JSONObject resutlJson = JSON.parseObject(msg);
            JSONArray result = resutlJson.getJSONArray("result");

            logger.info("短信发送成功：" + JSON.toJSONString(content));
            return ((JSONObject) result.get(0)).getInteger("return");
        } catch (Exception e) {
            logger.info("短信发送失败：" + JSON.toJSONString(content) + "，失败原因：" + e.getMessage());
            return -1;
        }

    }


}
